<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { createApi, getApiById, updateApi } from '#/api/sys/api';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema: [
    {
      component: 'Input',
      fieldName: 'path',
      label: $t('sys.apis.path'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        clearable: true,
      },
      fieldName: 'serviceName',
      help: $t('sys.apis.isRequiredHelpMessage'),
      label: $t('sys.apis.serviceName'),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'group',
      label: $t('sys.apis.group'),
      rules: 'required',
    },
    {
      component: 'Input',
      // 对应组件的参数
      fieldName: 'description',
      label: $t('sys.apis.description'),
      rules: 'required',
    },
    {
      component: 'Input',
      // 对应组件的参数
      fieldName: 'method',
      label: $t('sys.apis.method'),
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: '1',
      help: $t('sys.apis.isRequiredHelpMessage'),
      componentProps: {
        isButton: true,
        options: [
          {
            label: $t('common.form.yes'),
            value: '1',
          },
          {
            label: $t('common.form.no'),
            value: '0',
          },
        ],
      },
      fieldName: 'isRequired',
      label: $t('sys.apis.must'),
    },
  ],
});

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  loading: true, // 不显示加载中状态

  // 表单校验
  async onConfirm() {
    const isPass = await baseFormApi.validateAndSubmitForm(); // 校验表单
    const { type, id } = drawerApi.getData<Record<string, any>>();
    if (!isPass) {
      return; // 校验不通过
    }
    if (type === 'addData') {
      savePosition(isPass);
    }
    if (type === 'editData') {
      savePosition(isPass, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        drawerApi.setState({ loading: false });
        baseFormApi.resetForm();
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getPositionDetailInfo(id);
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增或编辑职位
 * @param {Record<string, any>} formData - 表单数据对象
 * @param {number} [id] - 职位ID（存在表示编辑，不存在表示新增）
 * @returns {void}
 */
async function savePosition(formData: any, id?: number): Promise<void> {
  try {
    const data = {
      ...formData,
      id,
      isRequired: formData.isRequired === '1',
    };
    id ? await updateApi(data) : await createApi(data);
    ElMessage.success('操作成功');
    emit('refresh');
  } catch (error) {
    ElMessage.error('操作失败');
    console.error(error);
  }
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {any} id - 要回显的职位ID。
 * @returns {void}
 */
async function getPositionDetailInfo(id: any): Promise<void> {
  try {
    await getApiById(id).then((res: any) => {
      baseFormApi.setValues({
        ...res,
        isRequired: res.isRequired ? '1' : '0',
      });
      // 关闭加载中状态
      drawerApi.setState({ loading: false });
    });
  } catch {
    ElMessage.error('获取详情失败');
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  }
}
</script>
